<template>
  <div id="paypal-button-container"></div>
  <div id="paypal-button-container2"></div>
</template>

<script setup>
import { onMounted } from 'vue';
import { loadScript } from '@paypal/paypal-js';

// 假设这是你的PayPal客户端ID
const clientId = import.meta.env.PAYPAL_CLIENT_ID;

onMounted(async () => {
  let paypal;
  try {
    // 加载PayPal JS SDK
    paypal = await loadScript({
      clientId: clientId,
      components: "buttons,funding-eligibility"
    });
  } catch (error) {
    console.error('Failed to load the PayPal JS SDK script', error);
    return;
  }

  if (paypal) {
    try {
      // Loop over each funding source / payment method
      paypal.getFundingSources().forEach(function(fundingSource) {
        // Initialize the buttons
        const button = paypal.Buttons({
          fundingSource: fundingSource
        });
        // Check if the button is eligible
        if (button.isEligible()) {
          // Render the standalone button for that funding source
          button.render('#paypal-button-container2');
        }
      });
    } catch (error) {
      console.error("failed to render the PayPal Buttons", error);
    }

    try {
      // 渲染PayPal按钮到指定的DOM元素
      await paypal.Buttons({
        style: {
          layout: 'vertical',
          color:  'gold',
          shape:  'pill',
          label:  'paypal'
        },
        // 这里可以配置你的PayPal按钮选项
        createOrder: async (data, actions) => {
          return await createOrder();
        },
        onApprove: async (data, actions) => {
          return await onApprove(data,actions);
        }
      }).render('#paypal-button-container');
    } catch (error) {
      console.error('Failed to render the PayPal Buttons', error);
    }
  }
});

async function createOrder() {
  try {
    const response = await fetch("/api/orders", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      // use the "body" param to optionally pass additional order information
      // like product ids and quantities
      body: JSON.stringify({
        cart: [
          {
            id: "1",
            quantity: "10",
          },
        ],
      }),
    });
    console.log(response)
    const orderData = await response.json();
    console.log(orderData)
    if (orderData.id) {
      return orderData.id;
    } else {
      const errorDetail = orderData?.details?.[0];
      const errorMessage = errorDetail
          ? `${errorDetail.issue} ${errorDetail.description} (${orderData.debug_id})`
          : JSON.stringify(orderData);

      throw new Error(errorMessage);
    }
  } catch (error) {
    console.error(error);
    return `Could not initiate PayPal Checkout...${error}`;
  }
}

async function onApprove(data, actions) {
  try {
    const response = await fetch(`/api/orders/${data.orderID}/capture`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
    });

    const orderData = await response.json();
    // Three cases to handle:
    //   (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart()
    //   (2) Other non-recoverable errors -> Show a failure message
    //   (3) Successful transaction -> Show confirmation or thank you message

    const transaction =
        orderData?.purchase_units?.[0]?.payments?.captures?.[0] ||
        orderData?.purchase_units?.[0]?.payments?.authorizations?.[0];
    const errorDetail = orderData?.details?.[0];

    if (errorDetail || !transaction || transaction.status === "DECLINED") {
      // (2) Other non-recoverable errors -> Show a failure message
      let errorMessage;
      if (transaction) {
        errorMessage = `Transaction ${transaction.status}: ${transaction.id}`;
      } else if (errorDetail) {
        errorMessage = `${errorDetail.description} (${orderData.debug_id})`;
      } else {
        errorMessage = JSON.stringify(orderData);
      }

      throw new Error(errorMessage);
    } else {
      // (3) Successful transaction -> Show confirmation or thank you message
      // Or go to another URL:  actions.redirect('thank_you.html');
      console.log(
          "Capture result",
          orderData,
          JSON.stringify(orderData, null, 2)
      );
      return `Transaction ${transaction.status}: ${transaction.id}. See console for all available details`;
    }
  } catch (error) {
    return `Sorry, your transaction could not be processed...${error}`;
  }
}
</script>

<style scoped>

</style>